import CryptoJS from 'crypto-js';
import Constant from '@/constant/Constants';
import Util from './Util';
import LoggerUtil from './LoggerUtil';
export default class CodecUtil {
    public static encrypt(data: any) {
        if (Util.isEmpty(data)) {
            return '';
        }
        let word = typeof data === 'object' ? JSON.stringify(Util.sortObject(data)) : `${data}`;
        if (Util.isEmpty(word)) {
            return word;
        }
        word = CryptoJS.enc.Utf8.parse(word);
        let key = CryptoJS.enc.Utf8.parse(Constant.aesKey);
        const encrypted = CryptoJS.AES.encrypt(word, key, {
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7,
            iv: CryptoJS.enc.Utf8.parse(Constant.aesKey)
        });
        const aseData = encrypted.ciphertext.toString().toUpperCase();
        return this.resetBase64(CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(aseData)));
    }

    public static sign(data: object): string {
        Reflect.deleteProperty(data, 'sign')
        const signSrc = Object.entries(data)
            .sort()
            .map(value => value.join('='))
            .concat(`key=${Constant.signKey}`)
            .join('&');

        const hexSign = CryptoJS.MD5(signSrc);
        return this.resetBase64(CryptoJS.enc.Base64.stringify(hexSign));
    }

    public static resetBase64(str: string, reduction: boolean = false): string {
        return reduction ? str.replace(/_/g, '/').replace(/-/g, '+') : str.replace(/\//g, '_').replace(/\+/g, '-');
    }
}